package com.gao.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gao.domain.Cart;
import com.gao.domain.User;
import com.gao.service.CartService;
import com.gao.service.impl.CartServiceImpl;

/**
 * Servlet implementation class CartAddServlet
 */
@WebServlet("/CartAddServlet")
public class CartAddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pidStr = request.getParameter("pid");
		//ע�⣺�˴������޸���
		String incrementStr = request.getParameter("num");
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute("user");
		if(user!=null){
			int uid = user.getUid();
			CartService cartService = new CartServiceImpl();
			cartService.addOrUpdateNumber(Integer.parseInt(incrementStr),Integer.parseInt(pidStr) , uid);
			List<Cart> carts = cartService.getCartsByUid(uid);
			//�����ܼƣ�����request
			double totalPrice = 0;
			for(Cart cart:carts){
				totalPrice += cart.getCartNum()*cart.getProduct().getPrice();
			}
			request.setAttribute("carts", carts);
			request.setAttribute("totalPrice", totalPrice);
			request.getRequestDispatcher("cart.jsp").forward(request, response);
		}else{
			//��ʾ��Ϣ
			request.setAttribute("msg", "���¼����й���");
			request.getRequestDispatcher("login.jsp").forward(request, response);
		}
		
		
	}

}
